import './login.scss'
import { useNavigate, useLocation } from 'react-router-dom'
import { setCookie } from '@/utils/auth'
import { Button, Form, Input, message } from 'antd'
import { LoginApi } from '@/api/user'
import { useDispatch } from 'react-redux'

function Login() {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const location = useLocation()

  const onFinish = async (values: { user_name: string; user_pwd: string }) => {
    const { code, data, msg } = await LoginApi(values)
    if (code !== 200) {
      return message.error(msg || '登录失败')
    }
    dispatch({
      type: 'add',
      payload: {
        id: data?.id,
        name: data?.user_name
      }
    })
    setCookie('USER_ID', data?.id)
    setCookie('USER_NAME', data?.user_name)
    setCookie('TOKEN', data?.token)

    // 重定向回去
    const params = new URLSearchParams(location.search)?.get('redirect')
    navigate(`${params || '/'}`)
  }

  return (
    <div className="login-page">
      <div className="login-box">
        <h2 className="login-heading">书签管理器</h2>
        <Form
          name="basic"
          layout="vertical"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="user_name"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input name="user_name" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="user_pwd"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password name="user_pwd" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
